package net.moonbiter.ebs.protocols.json;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.moonbiter.ebs.callers.OutputDeliverer;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

import org.apache.log4j.*;

public class JsonDeliverer implements OutputDeliverer<HttpServletResponse> {
	private final static Logger logger = Logger.getLogger(JsonDeliverer.class);
	
	private Map<String,Object> map;
	
	public JsonDeliverer(){
		map = new HashMap<String,Object>();
	}

	public void deliverError(HttpServletResponse output, Exception exception) throws IOException {
		map.put("error",exception);
		map.put("result",null);
		deliver(output, map);		
	}

	public void deliverResult(HttpServletResponse output, Object result) throws IOException {
		map.put("error",null);
		map.put("result",result);
		deliver(output, map);
	}
	
	private void deliver(HttpServletResponse output, Object javaObj) throws IOException{
		JSON jsonResult = JSONSerializer.toJSON(javaObj);
		PrintWriter writer = output.getWriter();
		writer.write(jsonResult.toString(3));
		writer.close();
	}

}
